package httplib

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"encoding/xml"
	"io"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net"
	"net/http"
	"net/http/cookiejar"
	"net/http/httputil"
	"net/url"
	"os"
	"strings"
	"sync"
	"time"
)

// 默认配置
const agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36"

var defaultSetting = HttpSettings{false, agent, 60 * time.Second, 60 * time.Second, nil, nil, nil}

// 配置锁
var settingMutex sync.Mutex

// cookie
var defaultCookieJar, _ = cookiejar.New(nil)

// HttpSettings
type HttpSettings struct {
	ShowDebug        bool
	UserAgent        string
	ConnectTimeout   time.Duration
	ReadWriteTimeout time.Duration
	TlsClientConfig  *tls.Config
	Proxy            func(*http.Request) (*url.URL, error)
	Transport        http.RoundTripper
}

func SetDefaultSetting(setting HttpSettings) {
	settingMutex.Lock()
	defer settingMutex.Unlock()
	defaultSetting = setting
	if defaultSetting.ConnectTimeout == 0 {
		defaultSetting.ConnectTimeout = 20 * time.Second
	}
	if defaultSetting.ReadWriteTimeout == 0 {
		defaultSetting.ReadWriteTimeout = 20 * time.Second
	}
}

type HttpRequest struct {
	url       string
	req       *http.Request
	params    map[string]string
	files     map[string]string
	setting   HttpSettings
	resp      *http.Response
	body      []byte
	cookieJar http.CookieJar
	cookieStr string
}

func NewRequest(url, method string) *HttpRequest {
	var resp http.Response
	req := http.Request{
		Method:     method,
		Header:     make(http.Header),
		Proto:      "HTTP/1.1",
		ProtoMajor: 1,
		ProtoMinor: 1,
	}
	return &HttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil, nil, ""}
}

// Get请求
func Get(url string) *HttpRequest {
	return NewRequest(url, "GET")
}

// Post请求
func Post(url string) *HttpRequest {
	return NewRequest(url, "POST")
}

// Put请求
func Put(url string) *HttpRequest {
	return NewRequest(url, "PUT")
}

// Patch请求
func Patch(url string) *HttpRequest {
	return NewRequest(url, "PATCH")
}

// Delete请求
func Delete(url string) *HttpRequest {
	return NewRequest(url, "DELETE")
}

// Head returns *HttpRequest with HEAD method.
func Head(url string) *HttpRequest {
	return NewRequest(url, "HEAD")
}

// 重置http设置
func (this *HttpRequest) Setting(setting HttpSettings) *HttpRequest {
	this.setting = setting
	return this
}

// SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
func (this *HttpRequest) SetBasicAuth(username, password string) *HttpRequest {
	this.req.SetBasicAuth(username, password)
	return this //
}

// SetEnableCookie sets   cookiejar
func (this *HttpRequest) UseCookieJar(jar http.CookieJar) *HttpRequest {
	if jar == nil {
		jar = defaultCookieJar
	}
	this.cookieJar = jar
	return this
}

// SetUserAgent sets User-Agent header field
func (this *HttpRequest) SetUserAgent(useragent string) *HttpRequest {
	this.setting.UserAgent = useragent
	return this
}

// Debug sets show debug or not when executing request.
func (this *HttpRequest) Debug(isdebug bool) *HttpRequest {
	this.setting.ShowDebug = isdebug
	return this
}

// SetTimeout sets connect time out and read-write time out for Request.
func (this *HttpRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *HttpRequest {
	this.setting.ConnectTimeout = connectTimeout
	this.setting.ReadWriteTimeout = readWriteTimeout
	return this
}

// SetTLSClientConfig sets tls connection configurations if visiting https url.
func (this *HttpRequest) SetTLSClientConfig(config *tls.Config) *HttpRequest {
	this.setting.TlsClientConfig = config
	return this
}

// Header add header item string in request.
func (this *HttpRequest) Header(key, value string) *HttpRequest {
	this.req.Header.Set(key, value)
	return this
}

// Set the protocol version for incoming requests.
// Client requests always use HTTP/1.1.
func (this *HttpRequest) SetProtocolVersion(vers string) *HttpRequest {
	if len(vers) == 0 {
		vers = "HTTP/1.1"
	}
	major, minor, ok := http.ParseHTTPVersion(vers)
	if ok {
		this.req.Proto = vers
		this.req.ProtoMajor = major
		this.req.ProtoMinor = minor
	}

	return this
}

// SetCookie add cookie into request.
func (this *HttpRequest) SetCookie(cookie *http.Cookie) *HttpRequest {
	this.cookieStr += cookie.Name + "=" + cookie.Value + ";"
	this.req.Header.Set("Cookie", this.cookieStr)
	return this
}

// Set transport to
func (this *HttpRequest) SetTransport(transport http.RoundTripper) *HttpRequest {
	this.setting.Transport = transport
	return this
}

// Set http proxy
// example:
//
//	func(req *http.Request) (*url.URL, error) {
//		u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
//		return u, nil
//	}
func (this *HttpRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *HttpRequest {
	this.setting.Proxy = proxy
	return this
}

// Param adds query param in to request.
// params build query string as ?key1=value1&key2=value2...
func (this *HttpRequest) Param(key, value string) *HttpRequest {
	this.params[key] = value
	return this
}

func (this *HttpRequest) PostFile(formname, filename string) *HttpRequest {
	this.files[formname] = filename
	return this
}

// Body adds request raw body.
// it supports string and []byte.
func (this *HttpRequest) Body(data interface{}) *HttpRequest {
	switch t := data.(type) {
	case string:
		bf := bytes.NewBufferString(t)
		this.req.Body = ioutil.NopCloser(bf)
		this.req.ContentLength = int64(len(t))
	case []byte:
		bf := bytes.NewBuffer(t)
		this.req.Body = ioutil.NopCloser(bf)
		this.req.ContentLength = int64(len(t))
	default:
		b, _ := json.Marshal(data)
		bf := bytes.NewBuffer(b)
		this.req.Body = ioutil.NopCloser(bf)
		this.req.ContentLength = int64(len(b))
	}
	return this
}

func (this *HttpRequest) getResponse() (*http.Response, error) {
	if this.resp.StatusCode != 0 {
		return this.resp, nil
	}
	var paramBody string
	if len(this.params) > 0 {
		var buf bytes.Buffer
		for k, v := range this.params {
			buf.WriteString(url.QueryEscape(k))
			buf.WriteByte('=')
			buf.WriteString(url.QueryEscape(v))
			buf.WriteByte('&')
		}
		paramBody = buf.String()
		paramBody = paramBody[0 : len(paramBody)-1]
	}

	if len(paramBody) > 0 && (this.req.Method == "GET" || this.req.Method == "DELETE") {
		if strings.Index(this.url, "?") != -1 {
			this.url += "&" + paramBody
		} else {
			this.url = this.url + "?" + paramBody
		}
	} else if this.req.Body == nil {
		if len(this.files) > 0 {
			pr, pw := io.Pipe()
			bodyWriter := multipart.NewWriter(pw)
			go func() {
				for formname, filename := range this.files {
					fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
					if err != nil {
						log.Fatal(err)
					}
					fh, err := os.Open(filename)
					if err != nil {
						log.Fatal(err)
					}
					//iocopy
					_, err = io.Copy(fileWriter, fh)
					fh.Close()
					if err != nil {
						log.Fatal(err)
					}
				}
				for k, v := range this.params {
					bodyWriter.WriteField(k, v)
				}
				bodyWriter.Close()
				pw.Close()
			}()
			this.Header("Content-Type", bodyWriter.FormDataContentType())
			this.req.Body = ioutil.NopCloser(pr)
		} else if len(paramBody) > 0 {
			this.Header("Content-Type", "application/x-www-form-urlencoded")
			this.Body(paramBody)
		}
	}

	url, err := url.Parse(this.url)
	if err != nil {
		return nil, err
	}

	this.req.URL = url

	trans := this.setting.Transport

	if trans == nil {
		// create default transport
		trans = &http.Transport{
			TLSClientConfig: this.setting.TlsClientConfig,
			Proxy:           this.setting.Proxy,
			Dial:            TimeoutDialer(this.setting.ConnectTimeout, this.setting.ReadWriteTimeout),
		}
	} else {
		// if this.transport is *http.Transport then set the settings.
		if t, ok := trans.(*http.Transport); ok {
			if t.TLSClientConfig == nil {
				t.TLSClientConfig = this.setting.TlsClientConfig
			}
			if t.Proxy == nil {
				t.Proxy = this.setting.Proxy
			}
			if t.Dial == nil {
				t.Dial = TimeoutDialer(this.setting.ConnectTimeout, this.setting.ReadWriteTimeout)
			}
		}
	}
	client := &http.Client{
		Transport: trans,
	}
	if this.cookieJar != nil {
		client.Jar = this.cookieJar
	}
	if len(this.setting.UserAgent) > 0 && len(this.req.Header.Get("User-Agent")) == 0 {
		this.req.Header.Set("User-Agent", this.setting.UserAgent)
	}

	if this.setting.ShowDebug {
		dump, err := httputil.DumpRequest(this.req, true)
		if err != nil {
			println(err.Error())
		}
		println(string(dump))
	}

	resp, err := client.Do(this.req)
	if err != nil {
		return nil, err
	}
	this.resp = resp
	return resp, nil
}

// String returns the body string in response.
// it calls Response inner.
func (this *HttpRequest) String() (string, error) {
	data, err := this.Bytes()
	if err != nil {
		return "", err
	}

	return string(data), nil
}

// Bytes returns the body []byte in response.
// it calls Response inner.
func (this *HttpRequest) Bytes() ([]byte, error) {
	if this.body != nil {
		return this.body, nil
	}
	resp, err := this.getResponse()
	if err != nil {
		return nil, err
	}
	if resp.Body == nil {
		return nil, nil
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	this.body = data
	return data, nil
}

// ToFile saves the body data in response to one file.
// it calls Response inner.
func (this *HttpRequest) ToFile(filename string) error {
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()

	resp, err := this.getResponse()
	if err != nil {
		return err
	}
	if resp.Body == nil {
		return nil
	}
	defer resp.Body.Close()
	_, err = io.Copy(f, resp.Body)
	return err
}

// ToJson returns the map that marshals from the body bytes as json in response .
// it calls Response inner.
func (this *HttpRequest) ToJson(v interface{}) error {
	data, err := this.Bytes()
	if err != nil {
		return err
	}
	err = json.Unmarshal(data, v)
	return err
}

// ToXml returns the map that marshals from the body bytes as xml in response .
// it calls Response inner.
func (this *HttpRequest) ToXml(v interface{}) error {
	data, err := this.Bytes()
	if err != nil {
		return err
	}
	err = xml.Unmarshal(data, v)
	return err
}

// Response executes request client gets response mannually.
func (this *HttpRequest) Response() (*http.Response, error) {
	return this.getResponse()
}

// TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.
func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
	return func(netw, addr string) (net.Conn, error) {
		conn, err := net.DialTimeout(netw, addr, cTimeout)
		if err != nil {
			return nil, err
		}
		conn.SetDeadline(time.Now().Add(rwTimeout))
		return conn, nil
	}
}
